/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package searchsort;

/**
 *
 * @author parallels
 */
public class QuickSort {
    
    public static MyDataBeanArray sort(MyDataBeanArray myArray) {
        sort(0, myArray.size()-1, myArray);
        return myArray;
        
    }
    
    private static void sort (int ini, int fin, MyDataBeanArray myArray) {
        
        int i = ini, j = fin;
        
        // Get the pivot element from the middle of the list
        int indPivot = ini + (fin - ini)/2;
        int pivot = myArray.get(indPivot).getKey();

        while (i<=j) {
            while (myArray.get(i).getKey() < pivot) {
                ++i;
            }
            while (myArray.get(j).getKey() > pivot) {
                --j;
            }
            if (i<=j) {
                exchange(i, j, myArray);
                ++i;
                --j;
            }
        }
        
        // recursion
        if (ini < j)
            sort(ini, j, myArray);
        if (i < fin) {
            sort(i, fin, myArray);
        }

    }
    
    private static void exchange (int i, int j, MyDataBeanArray myArray) {
        MyDataBean temp = myArray.get(i);
        myArray.set(i, myArray.get(j));
        myArray.set(j, temp);
    }
    
}
